package com.usian.behavior.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.usian.behavior.mapper.ApUnLikesBehaviorMapper;
import com.usian.behavior.service.ApBehaviorEntryService;
import com.usian.behavior.service.ApUnLikesBehaviorService;
import com.usian.model.behavior.dtos.UnLikesBehaviorDto;
import com.usian.model.behavior.pojos.ApBehaviorEntry;
import com.usian.model.behavior.pojos.ApUnlikesBehavior;
import com.usian.model.common.dtos.ResponseResult;
import com.usian.model.common.enums.AppHttpCodeEnum;
import com.usian.model.user.pojos.ApUser;
import com.usian.utils.threadlocal.AppThreadLocalUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

//不喜欢
@Service
public class ApUnLikesBehaviorServiceImpl extends ServiceImpl<ApUnLikesBehaviorMapper, ApUnlikesBehavior> implements ApUnLikesBehaviorService {

    @Autowired
    private ApBehaviorEntryService apBehaviorEntryService;


    @Override
    public ResponseResult unlike(UnLikesBehaviorDto dto) {
        //1.检查参数
        if (dto == null || dto.getArticleId() == null || dto.getType()==null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //2.查询行为实体
        ApUser user = AppThreadLocalUtils.getUser();//获取token里的用户id
        //根据用户id查询行为实体
        ApBehaviorEntry apBehaviorEntry = apBehaviorEntryService.findByUserIdOrEquipmentId(user.getId(), null);
        //如果该用户没有行为实体,就给他创一个
        if (apBehaviorEntry == null) {
            apBehaviorEntry = new ApBehaviorEntry();
            apBehaviorEntry.setCreatedTime(new Date());
            apBehaviorEntry.setEntryId(user.getId());
            apBehaviorEntry.setType((short) 1);
        }

        //3.不喜欢表里有没有记录
        ApUnlikesBehavior apUnlikesBehavior = getOne(Wrappers.<ApUnlikesBehavior>lambdaQuery().eq(ApUnlikesBehavior::getArticleId, dto.getArticleId()).eq(ApUnlikesBehavior::getEntryId, apBehaviorEntry.getId()));
        
        //0不喜欢1喜欢
        if (apUnlikesBehavior == null && dto.getType() == 0) {
            apUnlikesBehavior = new ApUnlikesBehavior();
            apUnlikesBehavior.setArticleId(dto.getArticleId());
            apUnlikesBehavior.setEntryId(apBehaviorEntry.getId());
            apUnlikesBehavior.setType(dto.getType().intValue());
            apUnlikesBehavior.setCreatedTime(new Date());
            save(apUnlikesBehavior);
        } else {
            //这一步判断的是只有他之前有行为实体,才能进行点赞与取消点赞的操作,如果没有的话直接做操作的话会报错
            if (dto.getType()==1) {
                apUnlikesBehavior.setType(dto.getType().intValue());
                updateById(apUnlikesBehavior);
            }
        }
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
}